package Server.Game;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;

public class QuestionGetter {
	
	int count;
	ArrayList<String> questions = new ArrayList<String>();
	ArrayList<String> anwsers = new ArrayList<String>();
	
	public QuestionGetter(){
		count = getQuestionCount();
		getQuestions();
	}
	
	private int getQuestionCount(){
		File file = new File("BoardQuiz_Kysimustik.xml");
		FileInputStream fstream = null;
		int count = 0;
		try {
			fstream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			System.out.println("BoardQuiz_Kysimustik.xml faili ei leitud!");
		}
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		while (true) {
			String a = null;
			try {
				a = br.readLine();
			} catch (IOException e) {
				System.out.println("Sisendi lugemise viga!");
				break;
			}
			if (a != null) {
				if(a.indexOf("kysimus") != -1){
					count++;
				}
			}else{
				break;
			}
		}
		try {
			fstream.close();
		} catch (IOException e) {
			System.out.println("Lugeri sulgemise viga!");
		}
		return count;
	}
	
	private void getQuestions() {
		File file = new File("BoardQuiz_Kysimustik.xml");
		FileInputStream fstream = null;
		try {
			fstream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			System.out.println("BoardQuiz.xml faili ei leitud!");
		}
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		while (true) {
			String a = null;
			try {
				a = br.readLine();
			} catch (IOException e) {
				System.out.println("Sisendi lugemise viga!");
				break;
			}
			if (a != null) {
				if(a.indexOf("kysimus") != -1){
					questions.add(a.substring(a.indexOf("kysimus") + 8, a.length() - 10));
					try {
						a = br.readLine();
					} catch (IOException e) {
						System.out.println("Sisendi lugemise viga!");
						break;
					}
					anwsers.add(a.substring(a.indexOf("vastus") + 7, a.length() - 9));
				}
			}else{
				break;
			}
		}
		try {
			fstream.close();
		} catch (IOException e) {
			System.out.println("Lugeri sulgemise viga!");
		}
	}

	public String[] getQuestion() {
		Random rnd = new Random();
		int question = rnd.nextInt(count);
		String[] res = new String[2];
		res[0] = questions.get(question);
		res[1] = anwsers.get(question);
		return res;
	}
}
